export type Options = { delay?: number, mount?: HTMLElement }

// 1) tip
export const message = {
  success: (msg: string, option: Options = {}) => message.create(msg, 'success', option),
  error: (msg: string, option: Options = {}) => message.create(msg, 'error', option),
  warn: (msg: string, option: Options = {}) => message.create(msg, 'warn', option),
  create(msg: string, type: string, option: Options = {}) {
    let { delay, mount } = option
    let div = document.createElement('div')
    let body = document.body
    div.innerText = msg
    div.className = `message ${type}`
    mount ? mount.appendChild(div) : body.appendChild(div)
    // 清除 dom
    if (delay) {
      return setTimeout(() => mount ? mount.removeChild(div) : body.removeChild(div), delay);
    }
    setTimeout(() => mount ? mount.removeChild(div) : body.removeChild(div), 1000);
  }
}

// 2) browser
export const copy = (content: string, success?: () => void, error?: (err: Error) => void) => {
  // 检查浏览器是否支持Clipboard API
  if (navigator.clipboard) {
    // 使用Clipboard API复制文本
    navigator.clipboard.writeText(content)
      .then(() => success && success())
      .catch(err => error && error(err));
  } else {
    console.error("浏览器不支持Clipboard API");
  }
}
export const downLoadFile = (fileUrl: string, fileName?: string) => {
  return new Promise<void>(async (resolve, reject) => {
    try {
      if (!fileUrl) return resolve()
      const response = await fetch(fileUrl);
      if (!response.ok) {
        throw new Error(`Error fetching MP4. Status: ${response.status}`);
      }
      const blob = await response.blob();
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(blob);
      if (fileName) { downloadLink.download = fileName };
      downloadLink.click();
      URL.revokeObjectURL(downloadLink.href);
      setTimeout(() => {
        resolve()
      }, 1000);
    } catch (error) {
      reject('Error downloading MP4:' + error)
    }
  })
}
// 一次性只能下载十个限制
export const splitTenArr = (urls: string[]) => {
  if (!Array.isArray([])) return []
  const _urls: string[][] = []
  let count = 0
  while (urls && urls.length > count) {
    _urls.push(urls.slice(count, count + 10))
    count += 10
  }
  return _urls
}
export const nextDownLoad = (imgs?: string[], getFileName?: (index: number) => string, lastDo: () => void = () => { }, count: number = 0) => {
  // 1 无值中断自循环
  if (!imgs || !imgs.length) lastDo()
  // 2 分割数组
  const arrs = splitTenArr(imgs as string[])
  // 3 判断执行
  if (arrs.length > 0) {
    const requestArr: any = []
    arrs[0].forEach((url, i) => requestArr.push(downLoadFile(url, getFileName ? getFileName(i + count) : undefined)))
    count += 10
    // 4 递归执行自身
    Promise.all(requestArr).then(res => {
      nextDownLoad(arrs[1], getFileName, lastDo, count)
    })
  }
}

// 3) chrome
// 3.1 获取当前页面id
export const getCurrentTabId = () => {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      resolve(tabs.length ? tabs[0].id : null)
    });
  })
}

